import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp.util import login_required

from bcuser import Login
from bcuser import BasecampAccountForm
from bcuser import is_login
from theme import render_header
from theme import render_footer
from cache import Cache

class MainPage(webapp.RequestHandler):
    @login_required 
    def get(self):
        module = str(self.request.get('m'))
        modules = self.load_module(only_name=True)

        if module == '':
            buffer = render_header('Basecamp report', modules=modules)
        elif module != '':
            content = self.load_module(module_name=module)
            buffer = render_header('Basecamp report', modules=modules, css=content[module]['css'])
            buffer += content[module]['content']

        buffer += render_footer() 
        self.response.out.write(buffer)

    def load_module(self, module_name = None, only_name = False):
        '''Import python script in specific place.'''

        # Default modules
        modules = (
                    'test',
                    'time.projects',
                    'time.my_today_time',
                    'time.alert',
                    'clearcache',
                  )

        if type(module_name) == str:
            modules = (module_name,)
        elif type(module_name) in (list, tuple):
            modules = module_name

        return_list = {}
        for module in modules:
            m = __import__('modules.' + module) 
            
            content = {'content':'', 'css':[]}
            if not only_name:
                try:
                    con = eval('m.' + module + '.content(self)')
                    css = eval('m.' + module + '.css(self)')
                except Exception, e:
                    con = e
                    css = ''

                if con != '':
                    content['content'] = unicode(con)

                if css != '':
                    content['css'] = unicode(css)

            name = eval('m.' + module + '.__doc__')
            content['name'] = name
            if name != '':
                return_list[module] = content

        return return_list


    

application = webapp.WSGIApplication(
                        [
                            ('/', MainPage),
                            ('/login', Login),
                            ('/account', BasecampAccountForm),
                        ],
                        debug=True)

    
def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
